package com.baixiaowen.xiaoaointerview.JVM原理篇;

import com.github.javafaker.Faker;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;

/**
 * 简单的WebSocket服务
 *
 * @author Baixiaowen
 */
public class WebOutOfMem {

    public static void main(String[] args) {
        // File
        // Client FD
        // ServerSocket 其实就是一个服务端的文件，存储的是客户端的文件描述符
        ExecutorService pool = new ForkJoinPool();
        Faker faker = new Faker();
        List<String> list = new ArrayList<>();
        try(ServerSocket serverSocket = new ServerSocket(8080)) {
            while (true) {
                Socket clientSocket = serverSocket.accept();
                pool.submit(() -> {
                    String resp = "HTTP1.1 200 OK\n\n";
                    try {
                        OutputStream ostream = clientSocket.getOutputStream();
                        resp += faker.shakespeare().asYouLikeItQuote();
                        // 这就是内存泄露，没有必要存的东西每次都多存一份
                        list.add(resp);
                        ostream.write(resp.getBytes(StandardCharsets.UTF_8));
                        ostream.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            clientSocket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
